from collections import deque

n, m = map(int, input().split())
board = [[] for _ in range(n)]
for _ in range(n):
    board[_] = list(map(int, list(input())))
q = int(input())
for _ in range(q):
    x, y, s = map(int, input().split())
    visited = set()
    que = deque()
    que.append([x, y, s, 0])
    while que:
        xi, yi, si, distance = que.popleft()
        xi -= 1
        yi -= 1
        if (xi, yi, si) in visited: continue
        visited.add((xi, yi, si))
        if board[xi][yi] == 3:
            print(distance)
            break
        if si == 0:
            if xi < 0 or xi >= n: continue
            if yi < 0 or yi >= m: continue
            if board[xi][yi] != 1: continue
        if si == 1:
            if xi < 0 or xi >= n: continue
            if yi < 0 or yi >= m: continue
            if yi + 1 >= m: continue

            if board[xi][yi] == 0: continue
            if board[xi][yi + 1] == 0: continue
        if si == 2:
            if xi < 0 or xi >= n: continue
            if yi < 0 or yi >= m: continue
            if xi + 1 >= n: continue

            if board[xi][yi] == 0: continue
            if board[xi + 1][yi] == 0: continue

        if si == 0:
            que.append([xi, yi + 1, 1, distance + 1])
            que.append([xi, yi - 2, 1, distance + 1])
            que.append([xi - 2, yi, 2, distance + 1])
            que.append([xi + 1, yi, 2, distance + 1])
        elif si == 1:
            que.append([xi + 1, yi, 1, distance + 1])
            que.append([xi - 1, yi, 1, distance + 1])
            que.append([xi, yi - 1, 0, distance + 1])
            que.append([xi, yi + 2, 0, distance + 1])
        elif si == 2:
            que.append([xi - 2, yi, 0, distance + 1])
            que.append([xi + 1, yi, 0, distance + 1])
            que.append([xi, yi - 1, 2, distance + 1])
            que.append([xi, yi + 1, 2, distance + 1])
    print(-1)
